<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Constants\Constant;
use App\Model\Activity;
use App\Model\UserScore;
use App\Model\UserScoreDetail;
use Carbon\Carbon;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Result;
use Hyperf\DbConnection\Db;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @Consumer(exchange="score", routingKey="activityShare", queue="activityShare", name ="ActivityShareConsumer", nums=1)
 */
class ActivityShareConsumer extends ConsumerMessage
{
    public function consumeMessage($data, AMQPMessage $message): string
    {
        $activity = Activity::query()->findOrFail($data['act_id']);
        if($activity->getAttribute("status") == Constant::ACTIVITY_STATUS_FINISH){
            return Result::ACK;
        }

        $query = UserScoreDetail::query()->where([['user_id',$data['user_id']],['origin',Constant::SCORE_ORIGIN_ACTIVITY_SHARE],['direction',Constant::DIRECTION_INC]])->whereDate("add_time",Carbon::now()->toDateString());

        if($query->count() >= 10){
            return Result::ACK;
        }

        if($data['user_id'] == $data['source_id']){
            return Result::ACK;
        }

        if($query->where('source_id',$data['source_id'])->exists()){
            return Result::ACK;
        }


        Db::transaction(function () use($data){
            $score = UserScore::query()->find($data['user_id']);
            $score->setAttribute("total",$score->getAttribute("total") + 1);
            $score->setAttribute("available",$score->getAttribute("available") + 1);
            $score->save();

            $score_detail = new UserScoreDetail();
            $score_detail->setAttribute("user_id",$data['user_id']);
            $score_detail->setAttribute("direction",Constant::DIRECTION_INC);
            $score_detail->setAttribute("origin",Constant::SCORE_ORIGIN_ACTIVITY_SHARE);
            $score_detail->setAttribute("source_id",$data['source_id']);
            $score_detail->setAttribute("score",1);
            $score_detail->setAttribute("remark","活动分享好友并访问获1积分");
            $score_detail->save();
        });

        return Result::ACK;
    }
}
